﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

#if UNITY_EDITOR
using UnityEditor;
#endif

public class BhvAngleClamp : MonoBehaviour
{
    [System.Serializable]
    public class ClampData
    {
        public bool enable = true;
        public ClampAxis axis;
        public float clampStart;
        public float clampEnd;
    }


    public ClampData[] clampData;

    public enum ClampAxis
    {
        Y,
        X,
        Z
    }

    public float WrapAngle(float value)
    {
        float angle = value - 180;

        if (angle > 0)
            return angle - 180;

        return angle + 180;
    }

    // Update is called once per frame
    void LateUpdate()
    {
        var angles = this.transform.localEulerAngles;
        for (int i = 0; i < clampData.Length; i++)
        {
            var clamp = clampData[i];
            var axis = clamp.axis;
            float clampStart = clamp.clampStart;
            float clampEnd = clamp.clampEnd;

            switch (axis)
            {
                case ClampAxis.Y:
                    float y = WrapAngle(angles.y);
                    if (y > clampEnd)
                    {
                        y = clampEnd;
                    }
                    if (y < clampStart)
                    {
                        y = clampStart;
                    }
                    angles.y = y;
                    break;
                case ClampAxis.X:
                    float x = WrapAngle(angles.x);
                    if (x > clampEnd)
                    {
                        x = clampEnd;
                    }
                    if (x < clampStart)
                    {
                        x = clampStart;
                    }
                    angles.x = x;
                    break;
                case ClampAxis.Z:
                    float z = WrapAngle(angles.z);
                    if (z > clampEnd)
                    {
                        z = clampEnd;
                    }
                    if (z < clampStart)
                    {
                        z = clampStart;
                    }
                    angles.z = z;
                    break;
            }
        }
        this.transform.localEulerAngles = angles;
    }
}
